package pl.kosmowska.ewelina.server.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;

import pl.kosmowska.ewelina.server.DefaultCategoryBean;
import pl.kosmowska.ewelina.server.ServerConstants;
import pl.kosmowska.ewelina.server.jdo.CategoryData;
import pl.kosmowska.ewelina.server.jdo.CategoryItemData;
import pl.kosmowska.ewelina.server.jdo.UserData;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class UserDataDAO extends JdoDAOImpl<UserData> {

	private static final Logger log = Logger.getLogger(UserDataDAO.class
			.getName());


	private static User getGoogleUser() {
		UserService userService = UserServiceFactory.getUserService();
		if (userService.isUserLoggedIn() == false) {
			return null;
		}
		User user = userService.getCurrentUser();
		return user;
	}

	public static Long getLoggedInUserId() {
		User user = getGoogleUser();
		if (user == null) {
			return null;
		}
		UserData userData = findUserDataByGoogleUserId(user.getUserId());
		if (userData == null) {
			return null;
		}
		if (userData.getId() == null) {
			return null;
		}

		Key key = userData.getKey();
		if (key == null) {
			return null;
		}

		return key.getId();
	}

	public UserData findUserData(String id) {
		if (id == null) {
			return null;
		}
		Key k = KeyFactory.stringToKey(id);
		PersistenceManager pm = getPersistenceManager();
		try {
			UserData e = pm.getObjectById(UserData.class, k);
			return e;
		} finally {
			pm.close();
		}
	}

	public UserData findUserDataByGoogleEmail(String googleEmail) {
		PersistenceManager pm = getPersistenceManager();
		try {
			javax.jdo.Query query = pm.newQuery("select from " + UserData.class.getName());
			query.setRange(0, 1);
			query.setFilter("googleEmail==\""+ googleEmail + "\"");
			List<UserData> list = (List<UserData>) query.execute();
			int size = list.size();
			if (size == 0) {
				return null;
			}
			Iterator<UserData> itr = list.iterator();
			UserData ud = itr.next();
			return ud;
		} catch (Exception e) {
			log.log(Level.SEVERE, "Error: UserData.findUserDataByGoogleEmail(googleEmail): googleEmail=" + googleEmail, e);
			e.printStackTrace();
		} finally {
			pm.close();
		}
		return null;
	}

	public static UserData findUserDataByGoogleUserId(String googleUserId) {
		PersistenceManager pm = getPersistenceManager();
		try {
			javax.jdo.Query query = pm.newQuery("select from " + UserData.class.getName());
			query.setRange(0, 1);
			query.setFilter("googleUserId==\"" + googleUserId + "\"");
			List<UserData> list = (List<UserData>) query.execute();
			int size = list.size();
			if (size == 0) {
				return null;
			}
			Iterator<UserData> itr = list.iterator();
			UserData ud = itr.next();
			return ud;
		} catch (Exception e) {
			log.log(Level.SEVERE, "Error: UserData.findUserDataByGoogleUserId(googleUserId): googleUserId=" + googleUserId, e);
			e.printStackTrace();
		} finally {
			pm.close();
		}
		return null;
	}


	public UserData createUserData() {
		UserData userData = null; 

		UserService userService = UserServiceFactory.getUserService();
		if (userService.isUserLoggedIn() == false) {
			UserData r = new UserData();
			r.setLoginUrl();
			//r.setLogoutUrl(); // not needed
			return r;
		}

		User u = userService.getCurrentUser();
		if (u == null) {
			UserData r = new UserData();
			r.setLoginUrl();
			//r.setLogoutUrl(); // not needed
			return r;
		}
		boolean newUser=false;
		// has the user been here before? lookup and or create
		userData = findUserDataByGoogleUserId(u.getUserId());
		if (userData == null) {
			userData = new UserData();
			newUser=true;
		}

		userData.setGoogleUserId(u.getUserId());
		userData.setGoogleEmail(u.getEmail());
		userData.setGoogleNickname(u.getNickname());
		//userData.setLoginUrl(); // not needed
		userData.setLogoutUrl();

		UserData persistedDate = persist(userData);
		
		if(newUser){
			createDefaultCategoriesForUser(persistedDate);
		}
		return persistedDate;
	}

	private void createDefaultCategoriesForUser(UserData userData) {
		List<DefaultCategoryBean> defaultCategoryList = ServerConstants.getDefaultCategoryList();
		List<CategoryData> categoryList = new ArrayList<CategoryData>();
		for(DefaultCategoryBean categoryBean:defaultCategoryList ){
			CategoryData categoryData = new CategoryData();
			categoryData.setName(categoryBean.getName());
			categoryData.setDefaultCategory(true);
			ArrayList<CategoryItemData> categoryItemList = new ArrayList<CategoryItemData>();
			for(String subCategoryName :categoryBean.getItems() ){
				CategoryItemData categoryItemData = new CategoryItemData();
				categoryItemData.setName(subCategoryName);
				categoryItemData.setDefaultCategory(true);
				categoryItemList.add(categoryItemData);
			}
			categoryData.setItems(categoryItemList);
			categoryList.add(categoryData);
		}
		CategoryDataDAO.persistDefaultCategoryList(categoryList);
		
	}

	public UserData persist(UserData userData) {
		return (UserData) persistEntity(userData);
	}


}